package handler

import (
	"github.com/gin-gonic/gin"
	"red-book-mgr/model"
	"strconv"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	var user model.User
	err := model.DB.Debug().Where("username=?", username).Find(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}
	if user.Password != password {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
	})
	return
}

func List(c *gin.Context) {
	page, _ := strconv.Atoi("page")
	size, _ := strconv.Atoi("size")
	offset := (page - 1) * size
	var book []model.Book
	model.DB.Offset(offset).Limit(size).Debug().Find(&book)
	var count int64
	model.DB.Model(&model.Book{}).Count(&count)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "success",
		"data":  book,
		"count": count,
	})
	return
}
